<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input v-model="queryParams.category" placeholder="请输入分类" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--<el-form-item label="难度" prop="level">-->
        <!--<el-input v-model="queryParams.level" placeholder="请输入难度" clearable style="width: 240px" @keyup.enter.native="handleQuery" />-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="编号" align="center" key="id" prop="id" v-if="columns[0].visible" width="80" />
      <el-table-column label="标题" align="center" key="title" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" key="category" prop="category" v-if="columns[2].visible" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="难度" align="center" key="level" prop="level" v-if="columns[3].visible" width="100" />
      <el-table-column label="时长" align="center" key="duration" prop="duration" v-if="columns[4].visible" width="120">
        <template slot-scope="scope">
          <span>{{ formatDuration(scope.row.duration) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="播放量" align="center" key="views" prop="views" v-if="columns[5].visible" width="100" />
      <el-table-column label="点赞数" align="center" key="likes" prop="likes" v-if="columns[6].visible" width="100" />
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改视频课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-input v-model="form.category" placeholder="请输入分类" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="难度" prop="level">
              <el-input v-model="form.level" placeholder="例如：初级/中级/高级" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时长(秒)" prop="duration">
              <el-input-number v-model="form.duration" :min="0" :step="10" :controls-position="'right'" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="播放量" prop="views">
              <el-input-number v-model="form.views" :min="0" :step="1" :controls-position="'right'" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点赞数" prop="likes">
              <el-input-number v-model="form.likes" :min="0" :step="1" :controls-position="'right'" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入描述" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="封面图" prop="thumbnail">
              <ImageUpload v-model="form.thumbnail" :limit="1" :file-type="['png','jpg','jpeg']" :file-size="5" :is-show-tip="true" />
            </el-form-item>
          </el-col>
                     <el-col :span="12">
             <el-form-item label="视频文件" prop="videoUrl">
               <FileUpload
                 ref="videoUpload"
                 v-model="form.videoUrl"
                 :limit="1"
                 :file-size="1024"
                 :file-type="['mp4','mov','avi','mkv','webm']"
                 :is-show-tip="true"
                 @input="handleVideoChange"
               />
             </el-form-item>
           </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="讲师姓名">
              <el-input v-model="form.instructor.name" placeholder="请输入讲师姓名" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="讲师头像">
              <ImageUpload v-model="form.instructor.avatar" :limit="1" :file-type="['png','jpg','jpeg']" :file-size="5" :is-show-tip="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
              <el-form-item label="外部链接" prop="jumpUrl">
                  <el-input v-model="form.jumpUrl" placeholder="请输入外部链接" maxlength="50" />
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="讲师简介">
              <el-input v-model="form.instructor.bio" type="textarea" placeholder="请输入讲师简介" maxlength="300" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频课程详情对话框 -->
    <el-dialog title="视频课程详情" :visible.sync="viewOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="编号">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ viewForm.title }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewForm.category }}</el-descriptions-item>
        <el-descriptions-item label="难度">{{ viewForm.level }}</el-descriptions-item>
        <el-descriptions-item label="时长">{{ formatDuration(viewForm.duration) }}</el-descriptions-item>
        <el-descriptions-item label="播放量">{{ viewForm.views }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ viewForm.likes }}</el-descriptions-item>
        <el-descriptions-item label="封面图" :span="2">
          <img v-if="viewForm.thumbnail" :src="resolveUrl(viewForm.thumbnail)" style="height: 80px" />
          <span v-else>暂无</span>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ viewForm.description || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="讲师姓名">{{ viewForm.instructor && viewForm.instructor.name }}</el-descriptions-item>
        <el-descriptions-item label="讲师头像">
          <img v-if="viewForm.instructor && viewForm.instructor.avatar" :src="resolveUrl(viewForm.instructor.avatar)" style="height: 60px" />
          <span v-else>暂无</span>
        </el-descriptions-item>
        <el-descriptions-item label="外部链接">{{ viewForm.jumpUrl }}</el-descriptions-item>
        <el-descriptions-item label="讲师简介" :span="2">{{ viewForm.instructor && viewForm.instructor.bio }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 15px;">
        <video v-if="viewForm.videoUrl" :src="resolveUrl(viewForm.videoUrl)" controls style="width: 100%; max-height: 420px; background: #000;" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideo, getVideo, delVideo, addVideo, updateVideo } from "@/api/video"
import ImageUpload from "@/components/ImageUpload"
import FileUpload from "@/components/FileUpload"

export default {
  name: "Video",
  components: { ImageUpload, FileUpload },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      videoList: [],
      title: "",
      open: false,
      viewOpen: false,
      dateRange: [],
             form: {
         id: undefined,
         title: undefined,
         description: "",
         category: "",
         jumpUrl: "",
         level: "",
         duration: 0,
         views: 0,
         likes: 0,
         thumbnail: "",
         videoUrl: "",
         instructor: {
           id: undefined,
           name: "",
           avatar: "",
           bio: ""
         }
       },
             viewForm: {
         id: undefined,
         title: "",
         description: "",
         category: "",
         jumpUrl: "",
         level: "",
         duration: 0,
         views: 0,
         likes: 0,
         thumbnail: "",
         videoUrl: "",
         instructor: {
           id: undefined,
           name: "",
           avatar: "",
           bio: ""
         }
       },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        category: undefined,
        level: undefined
      },
      columns: [
        { key: 0, label: `编号`, visible: true },
        { key: 1, label: `标题`, visible: true },
        { key: 2, label: `分类`, visible: true },
        { key: 3, label: `难度`, visible: true },
        { key: 4, label: `时长`, visible: true },
        { key: 5, label: `播放量`, visible: true },
        { key: 6, label: `点赞数`, visible: true }
      ],
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '标题长度必须介于 2 和 100 之间', trigger: 'blur' }
        ],
        category: [
          { required: true, message: "分类不能为空", trigger: "blur" },
          { min: 1, max: 50, message: '分类长度必须介于 1 和 50 之间', trigger: 'blur' }
        ],
        level: [
          { required: true, message: "难度不能为空", trigger: "blur" }
        ],
        duration: [
          { required: true, message: "时长不能为空", trigger: "change" }
        ],
        videoUrl: [
          { required: true, message: "请上传视频文件", trigger: "change" }
        ],

      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
         getList() {
       this.loading = true
       listVideo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
         // 解析列表数据中的 instructor 字段
         this.videoList = (response.rows || []).map(item => {
           if (item.instructor && typeof item.instructor === 'string') {
             try {
               item.instructor = JSON.parse(item.instructor)
             } catch (e) {
               console.warn('解析列表 instructor 失败:', e)
               item.instructor = { id: undefined, name: "", avatar: "", bio: "" }
             }
           } else if (!item.instructor) {
             item.instructor = { id: undefined, name: "", avatar: "", bio: "" }
           }
           return item
         })
         this.total = response.total
         this.loading = false
       })
     },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        description: "",
        category: "",
        jumpUrl: "",
        level: "",
        duration: 0,
        views: 0,
        likes: 0,
        thumbnail: "",
        videoUrl: "",
        instructor: {
          id: undefined,
          name: "",
          avatar: "",
          bio: ""
        }
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加视频课程"
    },
         handleUpdate(row) {
       this.reset()
       const id = row.id || this.ids
       getVideo(id).then(response => {
         const data = response.data || {}
         // 解析 instructor 字段（如果是 JSON 字符串）
         if (data.instructor && typeof data.instructor === 'string') {
           try {
             data.instructor = JSON.parse(data.instructor)
           } catch (e) {
             console.warn('解析 instructor 失败:', e)
             data.instructor = { id: undefined, name: "", avatar: "", bio: "" }
           }
         } else if (!data.instructor) {
           data.instructor = { id: undefined, name: "", avatar: "", bio: "" }
         }
         this.form = data
         this.open = true
         this.title = "修改视频课程"
       })
     },
         handleView(row) {
       getVideo(row.id).then(response => {
         const data = response.data || {}
         // 解析 instructor 字段（如果是 JSON 字符串）
         if (data.instructor && typeof data.instructor === 'string') {
           try {
             data.instructor = JSON.parse(data.instructor)
           } catch (e) {
             console.warn('解析 instructor 失败:', e)
             data.instructor = { id: undefined, name: "", avatar: "", bio: "" }
           }
         } else if (!data.instructor) {
           data.instructor = { id: undefined, name: "", avatar: "", bio: "" }
         }
         this.viewForm = data
         this.viewOpen = true
       })
     },
         submitForm() {
       this.$refs["form"].validate(valid => {
         if (!valid) return
         
         // 手动验证讲师姓名
         if (!this.form.instructor || !this.form.instructor.name || !this.form.instructor.name.trim()) {
           this.$modal.msgError("讲师姓名不能为空")
           return
         }
         
         // 去除首尾空格与默认值处理
         if (this.form.title) this.form.title = this.form.title.trim()
         if (this.form.category) this.form.category = this.form.category.trim()
         if (this.form.jumpUrl) this.form.jumpUrl = this.form.jumpUrl.trim()
         if (this.form.level) this.form.level = this.form.level.trim()
         if (this.form.description) this.form.description = this.form.description.trim()
         if (this.form.instructor) {
           if (this.form.instructor.name) this.form.instructor.name = this.form.instructor.name.trim()
           if (this.form.instructor.bio) this.form.instructor.bio = this.form.instructor.bio.trim()
         }

         // 准备提交的数据
         const submitData = { ...this.form }
         
        submitData.instructor = JSON.stringify(submitData.instructor)

         const api = submitData.id != undefined ? updateVideo : addVideo
         api(submitData).then(() => {
           this.$modal.msgSuccess(submitData.id ? "修改成功" : "新增成功")
           this.open = false
           this.getList()
         })
       })
     },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除视频编号为"' + ids + '"的数据项？').then(() => {
        return delVideo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 工具方法：格式化时长（秒 -> HH:mm:ss）
    formatDuration(totalSeconds) {
      if (!totalSeconds && totalSeconds !== 0) return '-'
      const sec = Math.max(0, parseInt(totalSeconds || 0))
      const h = Math.floor(sec / 3600)
      const m = Math.floor((sec % 3600) / 60)
      const s = sec % 60
      const pad = (n) => (n < 10 ? '0' + n : '' + n)
      return (h > 0 ? pad(h) + ':' : '') + pad(m) + ':' + pad(s)
    },
         // 兼容相对地址
     resolveUrl(url) {
       if (!url) return ''
       if (/^https?:\/\//i.test(url)) return url
       return (process.env.VUE_APP_BASE_API || '') + url
     },
     // 处理视频文件变化
     handleVideoChange(videoUrl) {
       if (videoUrl && !this.form.id) {
         // 只在新增时自动填充
         const fileName = this.getVideoFileName(videoUrl)
         
         // 自动填充标题（去除文件扩展名）
         if (!this.form.title || this.form.title.trim() === '') {
           this.form.title = fileName.replace(/\.[^/.]+$/, "")
         }
         
         // 自动填充分类（根据文件扩展名判断）
         if (!this.form.category || this.form.category.trim() === '') {
           const extension = fileName.split('.').pop().toLowerCase()
           if (['mp4', 'mov', 'avi', 'mkv', 'webm'].includes(extension)) {
             this.form.category = '视频教程'
           } else {
             this.form.category = '其他'
           }
         }
         
         // 尝试获取视频时长（这里需要后端支持，暂时设置为默认值）
         if (!this.form.duration || this.form.duration === 0) {
           // 如果后端能提供视频时长信息，可以在这里设置
           // 目前设置为默认值，用户需要手动填写
           this.form.duration = 1800 // 默认30分钟
         }
         
         // 显示成功提示
         this.$modal.msgSuccess("视频上传成功，基础信息已自动填充，请确认后完善其他信息")
       }
     },
     // 获取视频文件名
     getVideoFileName(videoUrl) {
       if (videoUrl.lastIndexOf("/") > -1) {
         return videoUrl.slice(videoUrl.lastIndexOf("/") + 1)
       } else {
         return videoUrl
       }
     }
  }
}
</script>

<style scoped>
.el-form-item__label {
  font-weight: 500;
}
</style>


